package com.demo.study.thread.compalteFuture;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

public class CompletableFutureExample {

    public static void main(String[] args) throws Exception {
        List<CompletableFuture<List<Map>>> futures = new ArrayList<>();

        CompletableFuture<List<Map>> future1 = CompletableFuture.supplyAsync(() -> getList1());
        futures.add(future1);

        CompletableFuture<List<Map>> future2 = CompletableFuture.supplyAsync(() -> getList2());
        futures.add(future2);

        CompletableFuture<List<Map>> future3 = CompletableFuture.supplyAsync(() -> getList3());
        futures.add(future3);

        CompletableFuture<Void> allFutures = CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]));

        CompletableFuture<List<Map>> combinedFuture = allFutures.thenApply(v -> {
            return futures.stream()
                    .map(CompletableFuture::join)
                    .flatMap(List::stream)
                    .collect(Collectors.toList());
        });

        List<Map> combinedList = combinedFuture.get();

        System.out.println(combinedList);
    }

    private static List<Map> getList1() {
        // 异步获取List1的逻辑
        return new ArrayList<>();
    }

    private static List<Map> getList2() {
        // 异步获取List2的逻辑
        return new ArrayList<>();
    }

    private static List<Map> getList3() {
        // 异步获取List3的逻辑
        return new ArrayList<>();
    }
}
